package pers.zh.parking.mvp.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import per.goweii.anylayer.AnyLayer;
import per.goweii.anylayer.Layer;
import pers.zh.parking.R;
import pers.zh.parking.data.UserSettings;
import pers.zh.parking.data.entity.Car;
import pers.zh.parking.di.component.DaggerMyCarsComponent;
import pers.zh.parking.mvp.contract.MyCarsContract;
import pers.zh.parking.mvp.presenter.MyCarsPresenter;
import pers.zh.parking.mvp.ui.adapter.MyCarsAdapter;
import pers.zh.parking.utils.MyUtils;
import pers.zh.parking.utils.UIUtils;
import pers.zjc.commonlibs.util.ObjectUtils;
import pers.zjc.commonlibs.util.ToastUtils;
import pers.zjc.commonlibs.util.VibrateUtils;

public class MyCarsActivity extends BaseActivity<MyCarsPresenter> implements MyCarsContract.View {

    private static final int TYPE_EDIT = 1;
    private static final int TYPE_ADD = 2;

    @BindView(R.id.ivLeft)
    ImageView ivLeft;
    @BindView(R.id.toolbar_left)
    RelativeLayout toolbarLeft;
    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.ivRight)
    ImageView ivRight;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.rl)
    SmartRefreshLayout rl;

    private MyCarsAdapter mAdapter;

    private boolean delModel; // 右上角图标控制变量,是否处于删除模式，默认为否

    private Layer layer;

    private List<Car> toDelCars = new ArrayList<>();
    private String formatTitle = "已选择%s项";

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerMyCarsComponent.builder().appComponent(appComponent).view(this).build().inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_reservation;
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        initView();
        mPresenter.loadData();
    }

    private void initView() {
        tvTitle.setText("我的车辆");
        ivRight.setImageDrawable(getDrawable(R.drawable.ic_add_24dp));
        mAdapter = new MyCarsAdapter(new ArrayList<>());
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(mAdapter);
        rl.setOnRefreshListener(refreshLayout -> mPresenter.loadData());
        mAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            Car item = mAdapter.getData().get(position);
            if (delModel) {
                // 删除模式下单击改背景
                if (item.isToDel()) {
                    toDelCars.remove(item);
                }
                else {
                    toDelCars.add(item);
                }
                item.setToDel(!item.isToDel());
                if (toDelCars.size() == 0) {
                    if (mAdapter.getData().isEmpty()) {
                        return;
                    }
                    for (Car car : mAdapter.getData()) {
                        car.setToDel(false);
                    }
                    updateToolBar();
                    mAdapter.notifyDataSetChanged();
                }
                else {
                    tvTitle.setText(String.format(this.formatTitle, toDelCars.size()));
                    mAdapter.notifyItemChanged(position);
                }
            }
            else {
                // 编辑操作
                showCarDialog(TYPE_EDIT, item);
            }
        });
        mAdapter.setOnItemLongClickListener((adapter, view, position) -> {
            if (!delModel) {
                VibrateUtils.vibrate(100L);
                // 开启删除模式
                Car car = (Car)adapter.getData().get(position);
                car.setToDel(true);
                toDelCars.add(car);
                mAdapter.notifyItemChanged(position);
                updateToolBar();
            }
            return true;
        });
        ivLeft.setOnClickListener(v -> {
            if (!delModel) {
                finish();
            }
            else {
                // 删除模式下，清空待删除列表
                toDelCars.clear();
                if (mAdapter.getData().isEmpty()) {
                    return;
                }
                for (Car car : mAdapter.getData()) {
                    car.setToDel(false);
                }
                // 点击叉叉关闭删除模式
                updateToolBar();
                mAdapter.notifyDataSetChanged();
            }

        });
        ivRight.setOnClickListener(v -> {
            if (delModel) {
                deleteCars();
            }
            else {
                showCarDialog(TYPE_ADD, null);
            }
        });
    }

    private void deleteCars() {
        UIUtils.createConfirmDialog(MyCarsActivity.this,
                String.format("是否要删除%s项数据?", toDelCars.size()), true, (dialog, which) -> {
                    mPresenter.delete(toDelCars);
                }, (dialog, which) -> {}).show();
    }

    private void showCarDialog(int type, Car item) {
        if (type == TYPE_EDIT) {
            if (item == null) {
                showMessage("参数错误");
                return;
            }
        }
        layer = AnyLayer.dialog(this)
                        .contentView(R.layout.popup_edit_car)
                        .backgroundColorRes(R.color.white)
                        .gravity(Gravity.CENTER)
                        .cancelableOnTouchOutside(true)
                        .cancelableOnClickKeyBack(true)
                        .backgroundDimAmount(0.5f)
                        .bindData(layer -> {
                            TextView tvTitle = layer.getView(R.id.tvTitle);
                            EditText etCarNo = layer.getView(R.id.etCarNo);
                            EditText etCarColor = layer.getView(R.id.etCarColor);
                            EditText etCarBrand = layer.getView(R.id.etCarBrand);
                            TextView tvConfirm = layer.getView(R.id.tvConfirm);
                            tvTitle.setText(type == TYPE_ADD ? "新增汽车" : "编辑汽车");
                            if (type == TYPE_EDIT) {
                                etCarNo.setText(item.getCarNo());
                                etCarColor.setText(item.getCarColor());
                                etCarBrand.setText(item.getCarBrand());
                            }
                            tvConfirm.setOnClickListener(v -> {
                                if (type == TYPE_ADD) {
                                    Car car = new Car();
                                    car.setCarNo(etCarNo.getText().toString());
                                    car.setCarColor(etCarColor.getText().toString());
                                    car.setCarBrand(etCarBrand.getText().toString());
                                    mPresenter.addCar(car);
                                }
                                else if (type == TYPE_EDIT) {
                                    item.setCarNo(etCarNo.getText().toString());
                                    item.setCarColor(etCarColor.getText().toString());
                                    item.setCarBrand(etCarBrand.getText().toString());
                                    mPresenter.updateCar(item);
                                }

                            });
                        });
        layer.show();
    }

    @Override
    public void showLoading() {
        rl.autoRefresh();
    }

    @Override
    public void hideLoading() {
        rl.finishRefresh();
    }

    @Override
    public void showMessage(@NonNull String message) {
        ToastUtils.showShort(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {

    }

    @Override
    public void killMyself() {

    }

    @Override
    public void showCars(List<Car> data) {
        if (ObjectUtils.isEmpty(data)) {
            mAdapter.setEmptyView(R.layout.layout_empty_view, recyclerView);
            return;
        }
        mAdapter.replaceData(data);
    }

    @Override
    public void success() {
        mPresenter.loadData();
        if (layer != null && layer.isShow()) {
            layer.dismiss();
        }
    }

    @Override
    public void delSuccess(List<Car> cars) {
        // UI删除
        Iterator<Car> it = mAdapter.getData().iterator();
        while (it.hasNext()) {
            Car car = it.next();
            if (cars.contains(car)) {
                it.remove();
            }
            mAdapter.notifyDataSetChanged();
        }
        toDelCars.clear();
        updateToolBar();
        showMessage("删除成功");
    }

    private void updateToolBar() {
        delModel = !delModel;
        ivLeft.setImageDrawable(
                !delModel ? getDrawable(R.drawable.ic_arrow_back_white_24dp) : getDrawable(
                        R.drawable.ic_close_black_24dp));
        ivRight.setImageDrawable(!delModel ? getDrawable(R.drawable.ic_add_24dp) : getDrawable(
                R.drawable.ic_delete_24dp));
        tvTitle.setText(delModel ? String.format(this.formatTitle, toDelCars.size()) : "我的车辆");
    }

}
